import { _decorator, Component, find, instantiate, Node, Prefab, randomRange, randomRangeInt } from 'cc';
import { SpawnState } from '../Global';
import { Zombie } from '../Zombie';
import { GameManager } from './GameManager';
import { AudioManager } from './AudioManager';
import { Config } from './Config';
const { ccclass, property } = _decorator;

@ccclass('ZombieManager')
export class ZombieManager extends Component {
    private static _instance: ZombieManager = null;

    private spawnState: SpawnState = SpawnState.NotStart;

    @property({ type: [Node] })
    spawnPointList: Node[] = [];
    @property(Prefab)
    zombiePrefab: Prefab = null;
    zombiesArray: Zombie[] = [];
    /**
     * 获取实例
     */
    public static get Instance(): ZombieManager {
        return this._instance;
    }
    protected onLoad(): void {
        //确保全局只有一个实例
        if (ZombieManager._instance == null) {
            ZombieManager._instance = this;
        } else {
            console.log("ZombieManager is already exist");
            this.node.destroy();
        }
    }
    protected onDestroy(): void {
        if(ZombieManager.Instance==this){
            ZombieManager._instance=null;
            this.node.destroy();
        }
    }
    protected update(dt: number): void {
        if(this.spawnState==SpawnState.End&&this.zombiesArray.length==0){
            GameManager.Instance.gameVictory();
    }
}
    startSpawn() {
        console.log("开始生成僵尸");
        this.spawnState = SpawnState.Spawning;
         this.startSpawnCoroutine();
    }
    /**
     * 异步函数实现协程
     */
    async startSpawnCoroutine() {
        console.log("协程开始");
        AudioManager.Instance.playClip(Config.siren);
        try {
            // 循环5次
            for (let i = 0; i < 5; i++) {
                console.log("第1波");
                this.spawnRandomZombie();// 生成随机僵尸
                await this.waitForSeconds(3);// 等待3秒
            }
            await this.waitForSeconds(1);// 等待1秒
            // 循环10次
            for (let i = 0; i < 10; i++) {
                console.log("第2波");
                this.spawnRandomZombie();// 生成随机僵尸
                await this.waitForSeconds(3);// 等待3秒
            }
            await this.waitForSeconds(1);// 等待1秒

            AudioManager.Instance.playClip(Config.lastwave);
            // 循环20次
            for (let i = 0; i < 20; i++) {
                console.log("第3波");
                this.spawnRandomZombie();// 生成随机僵尸
                await this.waitForSeconds(3);// 等待3秒
            }
        } catch (error) {
        console.log("协程错误: ", error);
        }
        console.log("协程结束");
        this.spawnState=SpawnState.End;
    }

    /**
     * 等待指定秒数的异步函数 
     */
   async waitForSeconds(seconds: number): Promise<void> {
        return new Promise((resolve, reject) => {
            this.scheduleOnce(() => {
                resolve();
            }, seconds);
        })
    }

    /**
     * 随机位置生成僵尸
     */
    spawnRandomZombie() {
        if (this.spawnState == SpawnState.Spawning) {
            let index = randomRangeInt(0, this.spawnPointList.length);
            let zombie = instantiate(this.zombiePrefab);
            this.zombiesArray.push(zombie.getComponent(Zombie));
            zombie.setParent(find("Canvas/Game/Zombies/layer"+index.toString()));
            zombie.setPosition(this.spawnPointList[index].position);
        }
    }

    removeZombie(zombie: Zombie) {
        this.zombiesArray.splice(this.zombiesArray.indexOf(zombie), 1);
    }

    Pause() {
        this.spawnState = SpawnState.End;
        for (let zombie of this.zombiesArray) {
            zombie.transitionToPause();
        }
    }
}

